#ifndef _MODULE_PROPERTY
#define _MODULE_PROPERTY
#include "page.module.js"
#include "prefs.module.js"
#include "boss.module.js"
#include "console.module.js"
#include "task.lib.js"
#include "ajax.lib.js"
#include "utility.lib.js"
#include "usolib.lib.js"

Modules.push( "Property" );

var Property = {
	count: 0,
	running: false,
	list: {},
	prop: null,
	log: function(action) {
		var log = [{
			name: 'Script',
			value: 'Property'
		},
		{
			name: 'Action',
			value: action
		}];
		Console.log(log);
		Console.status('property', action);
		return;
	},
	init: function(resume) {
		if (resume) {
			if (Property.running === false) return;
		}
		Property.count = 0;
		Property.log('Initiating the Property Automation');
		Property.running = true;
		Property.list = {};
		Property.prop = null;
		Ajax(Page.domain + '/mobwars/city/', function(xhr) {
			Property.update_list(xhr.responseText);
			return;
		});
		return;
	},
	update_list: function(html) {
		Property.log('Updating Property List');
		if (!html) {
			Ajax(Page.domain + '/mobwars/city/', function(xhr) {
				Page.captcha(xhr.responseText);
				if (Property.running === false) {
					return;
				};
				if (Page.pausing === true) {
					Page.pause_cb(function() {
						Property.update_list();
						return;
					});
					return;
				};
				Boss.update(xhr.responseText);
				Property.update_list(xhr.responseText);
				return;
			});
			return;
		}
		Property.list = {};
		var locations = [];
		var regex = new RegExp('"http://apps.facebook.com/mobwars/city/\\?show_loc=(.*?)"');
		Array.forEach(html.match(new RegExp('<a class="(lowerMenuHilighted|lowerMenuLink)" href="http://apps.facebook.com/mobwars/city/\\?show_loc=.*?"', 'g')), function(link) {
			locations.push(link.match(regex)[1]);
			return;
		});
		Property.locations = locations.length;
		Property.location_counter = 0;
		Array.forEach(locations, function(location) {
			GM_log(Page.domain + '/mobwars/city/?show_loc=' + location);
			Ajax(Page.domain + '/mobwars/city/?show_loc=' + location, function(xhr) {
				Page.captcha(xhr.responseText);
				if (Property.running === false)
					return;
				if (Page.pausing === true) {
					Page.pause_cb(function() {
						Property.update_list();
						return;
					});
					return;
				};
				Boss.update(xhr.responseText);
				Property.parse_location(xhr.responseText);
				Property.location_counter++;
				if (Property.location_counter >= Property.locations)
					Property.process();
				return;
			});
			return;
		});
		var timestamp = new Date().getTime();
		Property.timeout_timestamp = timestamp;
		var fn = function(time) {
			if (Property.running === false) {
				return;
			};
			if (Page.pausing === true) {
				Page.pause_cb(function() {
					Property.update_list();
					return;
				});
				return;
			};
			if (time == Property.timeout_timestamp) Property.update_list();
			return;
		};
		setTimeout(fn, 60000, timestamp);
		return;
	},
	parse_location: function(html) {
		var re_html = new RegExp('<a name="item_[0-9]*?"></a>(?:.|\\s)*?</form>', 'g'),
			html = html.match(re_html),
			name_re = new RegExp('<b style="font-size: 15px; color: silver;">(.*?)</b>'),
			cost_re = new RegExp('\\$([0-9]{1,4}(,[0-9]{3})*)</span>'),
			income_re = new RegExp('Income:.*?\\$([0-9]{1,4}(,[0-9]{3})*)'),
			req_re = new RegExp('<br />Built.+?On:.+?(.+?)(  )'),
			owned_re = new RegExp('([0-9]+?)</b></span>'),
			id_re = new RegExp('name="item" value="(.*?)"'),
			props = {},
			exclusions = [];
		for (i = html.length - 1; i >= 0; i--) {
			tr = html[i];
			var prop = {};
			prop.require = false;
			if (match = tr.match(name_re))
				prop.name = match[1];
			if (match = tr.match(id_re))
				prop.id = Utility.make_number(match[1]);
			if (match = tr.match(cost_re))
				prop.cost = Utility.make_number(match[1]);
			if (match = tr.match(income_re))
				prop.income = Utility.make_number(match[1]);
			if (match = tr.match(owned_re))
				prop.owned = Utility.make_number(match[1]);
			if (match = tr.match(req_re)) {
				prop.require = match[1];
				exclusions.push(prop.require);
			}
			if (prop.cost && prop.income) {
				prop.ror = (prop.income / prop.cost) * 100;
				if (10 <= prop.owned && !Settings.property_undev) {
					for (var j = exclusions.length - 1; j >= 0; j--) {
						if (prop.name == exclusions[j])
							prop.ror = -1;
					}
				}
			}
			props[prop.name] = prop;
		}
		for (prop_name in props) Property.list[prop_name] = props[prop_name];
		return;
	},
	process: function() {
		Property.timeout_timestamp = new Date().getTime();
		var props = [];
		for (property in Property.list) {
			props.push({
				name: property,
				ror: Property.list[property].ror
			});
		}
		props.sort(function(a, b) {
			return (b.ror - a.ror);
		});
		Property.prop = Property.list[props[0].name];
		if (Property.prop.require) {
			if (Property.list[Property.prop.require].owned < 10) {
				Property.prop = Property.list[Property.prop.require];
			}
		}
		Property.check_stats();
		return;
	},
	check_stats: function() {
		var prop = Property.prop;
		if (Property.running === false) return;
		if (Page.pausing === true) {
			Page.pause_cb(function() {
				Property.update_list();
				return;
			});
			return;
		};
		Property.log('Checking Boss\'s Stats');
		var updating = false;
		Settings.property_reserve = Settings.property_reserve || 0;
		if ((Boss.cash - Settings.property_reserve) < (prop.cost * 10)) {
			var timer = new Utility.timer({
				script: 'property',
				message: 'Re-checking for ' + Utility.int_dollars(prop.cost * 10) + ' to buy a ' + prop.name + ' in [[time]]...',
				time: 180,
				fn: function() {
					Property.log('Re-checking Boss\'s cash balance');
					if (Property.running === false) {
						return;
					};
					if (Page.pausing === true) {
						Page.pause_cb(function() {
							Property.update_list();
							return;
						});
						return;
					};
					Ajax(Page.domain + '/mobwars/city/', function(xhr) {
						Page.captcha(xhr.responseText);
						if (Property.running === false) {
							return;
						};
						if (Page.pausing === true) {
							Page.pause_cb(function() {
								Property.update_list();
								return;
							});
							return;
						};
						Boss.update(xhr.responseText);
						Property.update_list(xhr.responseText);
						return;
					});
					return;
				}
			});
			timer.start();
			return;
		}
		if (updating) {
			return;
		}
		Property.log('Stat checks complete');
		var wait = Page.wait();
		Property.log('Buying 10 ' + prop.name);
		var timer = new Utility.timer({
			script: 'property',
			message: 'Proceeding to buy 10 ' + prop.name + ' in [[time]]...',
			time: wait,
			fn: function() {
				if (Property.running === false) {
					return;
				};
				Property.buy();
				return;
			}
		});
		timer.start();
		return;
	},
	buy: function() {
		var prop = Property.prop;
		Ajax(Page.domain + '/mobwars/city/do.php?action=buy&qty=10&item=' + prop.id, function(xhr) {
			Property.count++;
			Page.captcha(xhr.responseText);
			if (Property.running === false) {
				return;
			};
			if (Page.pausing === true) {
				Page.pause_cb(function() {
					Property.update_list();
					return;
				});
				return;
			};
			Boss.update(xhr.responseText);
			Task.announce(xhr.responseText);
			Property.update_list(xhr.responseText);
			return;
		},
		'POST');
		return;
	}
};
#endif
